import React, { useState, useEffect } from 'react';
import {
  Button,
  Input,
  Label,
  Text,
  Select,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  Card,
  CardContent,
  CardHeader,
  CardTitle
} from 'packages/ui-shared/src/atoms';
import { getMarketDepartments } from '../mock/marketDepartmentData';
import { getClasses } from '../mock/classData';
import { getColleges } from '../mock/collegeData';

interface InputFormProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  onSubmit: (data: StudentInputData | StudentInputData[]) => void;
  mode?: 'single' | 'batch';
}

interface StudentInputData {
  name: string;
  gender: string;
  dateOfBirth: string;
  idNumber: string;
  marketingDepartment: string;
  class: string;
  college: string;
  [key: string]: any;
}

const InputForm: React.FC<InputFormProps> = ({
  isOpen,
  onOpenChange,
  onSubmit,
  mode = 'single'
}) => {
  const [activeMode, setActiveMode] = useState<'single' | 'batch'>(mode);
  const [form, setForm] = useState<StudentInputData>({
    name: '',
    gender: '男',
    dateOfBirth: '',
    idNumber: '',
    marketingDepartment: '',
    class: '',
    college: ''
  });
  const [batchData, setBatchData] = useState<StudentInputData[]>([
    {
      name: '',
      gender: '男',
      dateOfBirth: '',
      idNumber: '',
      marketingDepartment: '',
      class: '',
      college: ''
    }
  ]);
  const [departments, setDepartments] = useState<{ id: number; name: string }[]>([]);
  const [classes, setClasses] = useState<{ id: number; name: string }[]>([]);
  const [colleges, setColleges] = useState<{ id: number; name: string }[]>([]);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  useEffect(() => {
    // 加载市场部、班级和学院数据
    const loadData = async () => {
      try {
        const [deptData, classData, collegeData] = await Promise.all([
          getMarketDepartments(),
          getClasses(),
          getColleges()
        ]);
        setDepartments(deptData);
        setClasses(classData);
        setColleges(collegeData);
      } catch (error) {
        console.error('加载数据失败:', error);
      }
    };

    loadData();
  }, []);

  // 重置表单
  const resetForm = () => {
    setForm({
      name: '',
      gender: '男',
      dateOfBirth: '',
      idNumber: '',
      marketingDepartment: '',
      class: '',
      college: ''
    });
    setBatchData([
      {
        name: '',
        gender: '男',
        dateOfBirth: '',
        idNumber: '',
        marketingDepartment: '',
        class: '',
        college: ''
      }
    ]);
    setErrors({});
  };

  // 身份证验证函数
  const validateIdNumber = (idNumber: string): boolean => {
    // 简化的身份证验证逻辑
    const regex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return regex.test(idNumber);
  };

  // 验证表单
  const validateForm = (data: StudentInputData): boolean => {
    const newErrors: { [key: string]: string } = {};
    
    if (!data.name.trim()) {
      newErrors.name = '姓名不能为空';
    }
    
    if (!data.dateOfBirth) {
      newErrors.dateOfBirth = '出生日期不能为空';
    }
    
    if (!data.idNumber.trim()) {
      newErrors.idNumber = '身份证号不能为空';
    } else if (!validateIdNumber(data.idNumber)) {
      newErrors.idNumber = '请输入有效的身份证号';
    }
    
    if (!data.marketingDepartment) {
      newErrors.marketingDepartment = '请选择市场部';
    }
    
    if (!data.class) {
      newErrors.class = '请选择班级';
    }
    
    if (!data.college) {
      newErrors.college = '请选择学院';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理单个表单输入变化
  const handleSingleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 处理批量表单输入变化
  const handleBatchInputChange = (index: number, e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    const newBatchData = [...batchData];
    newBatchData[index] = { ...newBatchData[index], [name]: value };
    setBatchData(newBatchData);
  };

  // 添加新的批量输入行
  const addBatchRow = () => {
    setBatchData([...batchData, {
      name: '',
      gender: '男',
      dateOfBirth: '',
      idNumber: '',
      marketingDepartment: '',
      class: '',
      college: ''
    }]);
  };

  // 删除批量输入行
  const removeBatchRow = (index: number) => {
    if (batchData.length > 1) {
      const newBatchData = batchData.filter((_, i) => i !== index);
      setBatchData(newBatchData);
    }
  };

  // 提交表单
  const handleSubmit = () => {
    if (activeMode === 'single') {
      if (validateForm(form)) {
        onSubmit(form);
        resetForm();
        onOpenChange(false);
      }
    } else {
      // 验证批量数据中的每一行
      const validData = batchData.filter(row => validateForm(row));
      if (validData.length > 0) {
        onSubmit(validData);
        resetForm();
        onOpenChange(false);
      }
    }
  };

  // 当对话框打开时重置表单
  useEffect(() => {
    if (isOpen) {
      resetForm();
    }
  }, [isOpen]);

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>学生信息录入</DialogTitle>
          <DialogDescription>
            请填写学生信息，支持单条或批量录入
          </DialogDescription>
        </DialogHeader>
        
        <Tabs value={activeMode} onValueChange={(value) => setActiveMode(value as 'single' | 'batch')} className="mt-4">
          <TabsList>
            <TabsTrigger value="single">单条录入</TabsTrigger>
            <TabsTrigger value="batch">批量录入</TabsTrigger>
          </TabsList>
          
          <TabsContent value="single" className="space-y-4 mt-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">姓名</Label>
              <Input
                id="name"
                name="name"
                value={form.name}
                onChange={handleSingleInputChange}
                className={`col-span-3 ${errors.name ? 'border-red-500' : ''}`}
                required
              />
              {errors.name && <Text className="text-red-500 col-span-3 col-start-2">{errors.name}</Text>}
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="gender" className="text-right">性别</Label>
              <select
                id="gender"
                name="gender"
                value={form.gender}
                onChange={handleSingleInputChange}
                className="col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"
                required
              >
                <option value="男">男</option>
                <option value="女">女</option>
                <option value="其他">其他</option>
              </select>
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="dateOfBirth" className="text-right">出生日期</Label>
              <Input
                id="dateOfBirth"
                name="dateOfBirth"
                type="date"
                value={form.dateOfBirth}
                onChange={handleSingleInputChange}
                className={`col-span-3 ${errors.dateOfBirth ? 'border-red-500' : ''}`}
                required
              />
              {errors.dateOfBirth && <Text className="text-red-500 col-span-3 col-start-2">{errors.dateOfBirth}</Text>}
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="idNumber" className="text-right">身份证号</Label>
              <Input
                id="idNumber"
                name="idNumber"
                value={form.idNumber}
                onChange={handleSingleInputChange}
                className={`col-span-3 ${errors.idNumber ? 'border-red-500' : ''}`}
                required
              />
              {errors.idNumber && <Text className="text-red-500 col-span-3 col-start-2">{errors.idNumber}</Text>}
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="marketingDepartment" className="text-right">市场部</Label>
              <select
                id="marketingDepartment"
                name="marketingDepartment"
                value={form.marketingDepartment}
                onChange={handleSingleInputChange}
                className={`col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white ${errors.marketingDepartment ? 'border-red-500' : ''}`}
                required
              >
                <option value="">请选择市场部</option>
                {departments.map(dept => (
                  <option key={dept.id} value={dept.name}>{dept.name}</option>
                ))}
              </select>
              {errors.marketingDepartment && <Text className="text-red-500 col-span-3 col-start-2">{errors.marketingDepartment}</Text>}
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="class" className="text-right">班级</Label>
              <select
                id="class"
                name="class"
                value={form.class}
                onChange={handleSingleInputChange}
                className={`col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white ${errors.class ? 'border-red-500' : ''}`}
                required
              >
                <option value="">请选择班级</option>
                {classes.map(cls => (
                  <option key={cls.id} value={cls.name}>{cls.name}</option>
                ))}
              </select>
              {errors.class && <Text className="text-red-500 col-span-3 col-start-2">{errors.class}</Text>}
            </div>
            
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="college" className="text-right">学院</Label>
              <select
                id="college"
                name="college"
                value={form.college}
                onChange={handleSingleInputChange}
                className={`col-span-3 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white ${errors.college ? 'border-red-500' : ''}`}
                required
              >
                <option value="">请选择学院</option>
                {colleges.map(college => (
                  <option key={college.id} value={college.name}>{college.name}</option>
                ))}
              </select>
              {errors.college && <Text className="text-red-500 col-span-3 col-start-2">{errors.college}</Text>}
            </div>
          </TabsContent>
          
          <TabsContent value="batch" className="mt-4">
            <div className="overflow-x-auto">
              <table className="min-w-full">
                <thead>
                  <tr>
                    <th className="px-4 py-2 text-left">姓名</th>
                    <th className="px-4 py-2 text-left">性别</th>
                    <th className="px-4 py-2 text-left">出生日期</th>
                    <th className="px-4 py-2 text-left">身份证号</th>
                    <th className="px-4 py-2 text-left">市场部</th>
                    <th className="px-4 py-2 text-left">班级</th>
                    <th className="px-4 py-2 text-left">学院</th>
                    <th className="px-4 py-2 text-left">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {batchData.map((row, index) => (
                    <tr key={index} className="border-t">
                      <td className="px-4 py-2">
                        <Input
                          name="name"
                          value={row.name}
                          onChange={(e) => handleBatchInputChange(index, e)}
                          className="w-full"
                        />
                      </td>
                      <td className="px-4 py-2">
                        <select
                          name="gender"
                          value={row.gender}
                          onChange={(e) => handleBatchInputChange(index, e)}
                          className="w-full px-2 py-1 border border-gray-300 rounded"
                        >
                          <option value="男">男</option>
                          <option value="女">女</option>
                          <option value="其他">其他</option>
                        </select>
                      </td>
                      <td className="px-4 py-2">
                        <Input
                          name="dateOfBirth"
                          type="date"
                          value={row.dateOfBirth}
                          onChange={(e) => handleBatchInputChange(index, e)}
                          className="w-full"
                        />
                      </td>
                      <td className="px-4 py-2">
                        <Input
                          name="idNumber"
                          value={row.idNumber}
                          onChange={(e) => handleBatchInputChange(index, e)}
                          className="w-full"
                        />
                      </td>
                      <td className="px-4 py-2">
                        <select
                          name="marketingDepartment"
                          value={row.marketingDepartment}
                          onChange={(e) => handleBatchInputChange(index, e)}
                          className="w-full px-2 py-1 border border-gray-300 rounded"
                        >
                          <option value="">请选择</option>
                          {departments.map(dept => (
                            <option key={dept.id} value={dept.name}>{dept.name}</option>
                          ))}
                        </select>
                      </td>
                      <td className="px-4 py-2">
                        <select
                          name="class"
                          value={row.class}
                          onChange={(e) => handleBatchInputChange(index, e)}
                          className="w-full px-2 py-1 border border-gray-300 rounded"
                        >
                          <option value="">请选择</option>
                          {classes.map(cls => (
                            <option key={cls.id} value={cls.name}>{cls.name}</option>
                          ))}
                        </select>
                      </td>
                      <td className="px-4 py-2">
                        <select
                          name="college"
                          value={row.college}
                          onChange={(e) => handleBatchInputChange(index, e)}
                          className="w-full px-2 py-1 border border-gray-300 rounded"
                        >
                          <option value="">请选择</option>
                          {colleges.map(college => (
                            <option key={college.id} value={college.name}>{college.name}</option>
                          ))}
                        </select>
                      </td>
                      <td className="px-4 py-2">
                        <Button
                          variant="destructive"
                          size="sm"
                          onClick={() => removeBatchRow(index)}
                          disabled={batchData.length <= 1}
                        >
                          删除
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Button variant="outline" onClick={addBatchRow} className="mt-4">
              添加一行
            </Button>
          </TabsContent>
        </Tabs>
        
        <DialogFooter className="mt-4">
          <DialogClose asChild>
            <Button variant="outline">取消</Button>
          </DialogClose>
          <Button onClick={handleSubmit}>提交</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default InputForm;